/**
 * Created by kevin on 2017/6/15.
 */
/**
 * Created by kevin on 2017/6/7.
 */
var model= require('./model');
require('../utils/date');

var Applications = model.createModel({
    name : String, // 汇拾商盟
    bundleId : String, // 标识，
    version : String,
    iconUrl : String,
    type : Number, // 1 ios 2 android
    gitlab : String,
    branch : String,
    teamId : String, // ios专用
    projectName : String,
    build : {type:Number,default:0},
    gitUser : {type:model.objId,ref:'GitUsers'},
    configuration : {type:String,default:'Release'},
    sign : String, // ios 签名证书
    gitPath : {type:String,default:''},
    status : {type:Number,default:0}, // -1 禁止 0 正常 1 打包中
    robots : [{type:model.objId,ref:'Robots'}],
    ptime : {type : Date,default:Date.now},
    ctime : {type : Date,default:Date.now}
},'Applications');

Applications.cleanArchiving = function () {
    Applications.update({status:1},{$set:{status:0}},{multi: true},function (err,data) {
        console.log("已清理打包中APP");
    });
};

Applications.getListByType = function(type,callback) {

    Applications.find({type:type},null,{ lean: true ,sort:{ctime:-1}}).populate('robots').populate('gitUser').exec(function (err,list) {
        callback(err,list);
    });
};

Applications.getAll = function(callback) {
    Applications.find({},null,{ lean: true ,sort:{ctime:-1}}).populate('robots').populate('gitUser').exec(function (err,list) {
        callback(err,list);
    });
};

Applications.getById = function (id,callback) {
    Applications.findById(id,null,{ lean: true ,sort:{ctime:-1}}).populate('robots').populate('gitUser').exec(function (err,app) {
        callback(err,app);
    });
};

Applications.createUniqueName = function (doc,callback) {
    Applications.findOne({name : doc.name,type: doc.type},function (err,delegater) {
        if (delegater) {
            if (callback) {
                callback(new Error('应用已存在',null));
            }
        } else  {
            Applications.create(doc,callback);
        }
    });
};

Applications.edit = function (id,doc,callback) {
    console.log(JSON.stringify(doc));
    Applications.findByIdAndUpdate(id, doc, callback);
};


module.exports= Applications;
